<template>
    <view class="container">
        <view class="container-btn">
            <button class="index-title-btn" open-type="getPhoneNumber"  type="primary" @getphonenumber="onGetPhoneNumber">授权手机号登录</button>
        </view>
        <view class="container-btn">
            <button class="index-title-btn" open-type="getUserInfo" type="primary" @getuserinfo="onGetUserInfo">抖音一键登录</button>
        </view>
       <view class="container-btn">
            <button class="index-title-btn" type="primary" @tap="handleLogin">微信一键登录</button>
       </view>
  </view>
</template>
<script setup>
import { request } from '../utils/request.js'
// 用户信息
const getUserInfo = async() => {
    await request({
        url: '/user/info',
        method: 'POST',
        data: {}
    }).then(res => {
        if(res.code !== 200) {
			uni.showToast({
				title: res.data.message || '获取失败',
				icon: 'none',
                duration: 3000
			})
            return
		}
        uni.setStorageSync('userInfo', res.data)
        uni.switchTab({
            url: '/pages/index/index'
        })
    })
}
// 手机号登录
const onGetPhoneNumber = async (e) => {
    console.log(e.detail)
    const platform = uni.getSystemInfoSync().uniPlatform
    const platforms = platform === 'mp-weixin' ? 1 : 2
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
        const { encryptedData, iv, code } = e.detail
        // 先用 uni.login 获取临时 code
        uni.login({
            provider: platforms,
            success(loginRes) {
                const jsCode = loginRes.code
                request({
                    url: '/user/oauth/phone',
                    method: 'POST',
                    data: {
                        platform: platforms,    
                        code: jsCode || code,
                    },
                    success(res){
                        console.log('手机号获取成功：', res.data)
                        uni.setStorageSync('token', res.data)
                        getUserInfo()
                    }
                })
            }
        })
    } else {
        uni.showToast({ title: '授权失败', icon: 'none', duration: 3000 })
    }
}

// 抖音登录
const onGetUserInfo = async (e) => {
    const { userInfo, errMsg } = e.detail;
    const loginRes = await new Promise((resolve, reject) => {
        uni.login({
        provider: 'toutiao',
            success: res => resolve(res),
            fail: err => reject(err)
        })
    });
    const {code} = loginRes;
    if (code) {
        // 登录成功，获取到 anonymousCode
        const params = {
            code: code,
            platform: 2,
            userInfo: userInfo
          };
          console.log('登录成功：', params);
        // 将 anonymousCode 发送给后端
        const res = await request({
            url: '/user/login',
            method: 'POST',
            data: params
        })
        if(res.code !== 200) {
			uni.showToast({
				title: res.data.message || '登录失败',
				icon: 'none',
                duration: 3000
			})
            return
		}
        console.log('登录成功：', res);
        uni.setStorageSync('token', res.data.accessToken)
        uni.setStorageSync('refreshToken', res.data.refreshToken)
        getUserInfo()
    } else {
        console.error('获取 anonymousCode 失败:', errMsg)
        uni.showToast({ title: '授权失败', icon: 'none', duration: 3000 })
    }
}
// 授权登录
const handleLogin = async() => {
    uni.getUserProfile({
        desc: '用于完善会员资料',
        success: async (profileRes) => {
          const userInfo = profileRes.userInfo;

          // ✅ Step 2: 再去获取 code
          const loginRes = await new Promise((resolve, reject) => {
            uni.login({
              provider: 'weixin',
              success: resolve,
              fail: reject
            });
          });

          const code = loginRes.code;
          const params = {
            code: code,
            platform: 1,
            userInfo: userInfo
          };
         // ✅ Step 3: 提交给后端
        const res = await request({
            url: '/user/login',
            method: 'POST',
            data: params
        })
        if(res.code !== 200) {
			uni.showToast({
				title: res.data.message || '登录失败',
				icon: 'none',
                duration: 3000
			})
            return
		}
            console.log('登录成功：', res);
            uni.setStorageSync('token', res.data.accessToken)
            uni.setStorageSync('refreshToken', res.data.refreshToken)
            getUserInfo()
        },
        fail: (err) => {
          console.log('用户拒绝授权：', err);
        }
    });
};
</script>
<style scoped>
.container{
    position: absolute;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%)
}
.container-btn{
    margin-bottom: 30rpx;
}
.index-title-btn{
    background-color: #2b65f6;
    color: #fff;
    border-radius: 10rpx;
    height: 80rpx;
    line-height: 80rpx;
    width: 200px;
}
</style>